<?php

namespace app\admin\controller\prl;

use app\common\controller\Backend;
use app\admin\model\prl\Models as ModelsModel;
use think\Db;
use app\admin\model\prl\Viewsfields as ViewsfieldsModel;
use app\admin\model\prl\Channelsviewvalues;
use app\common\model\Config as ConfigModel;
/**
 * 栏目管理
 *
 * @icon fa fa-circle-o
 */
class Channels extends Backend
{
    protected $channelsList = [];
    /**
     * Channels模型对象
     * @var \app\admin\model\prl\Channels
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\prl\Channels;

        $this->channelsList = $this->model->getTreeArray();
        $channelsList = [0 => ['name' => __('TopColumn')]];
        foreach ($this->channelsList as $k => $v)
        {
            $channelsList[$v['id']] = $v;
        }
        
        $this->view->assign("parentList", $channelsList);
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("displayList", $this->model->getDisplayList());
        $this->view->assign("jumpChildList", $this->model->getJumpChildList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $list = [];
            foreach ($this->channelsList as $key => $value) {
                $value['name'] = html_entity_decode($value['name']);
                $list[] = $value;
            }
            $total = count($list);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    //选中模型返回模型视图
    public function getModelsViews()
    {
        $id = $this->request->param('id');
        $info = ModelsModel::get($id);
        $this->success('','',$info->toArray());
    }

    /**
     * 排序 解决数据库表不正确问题
     */
    public function weigh()
    {
        //排序的数组
        $ids = $this->request->post("ids");
        //拖动的记录ID
        $changeid = $this->request->post("changeid");
        //操作字段
        $field = $this->request->post("field");
        //操作的数据表
        $table = $this->request->post("table");
        //排序的方式
        $orderway = $this->request->post("orderway", "", 'strtolower');
        $orderway = $orderway == 'asc' ? 'ASC' : 'DESC';
        $sour = $weighdata = [];
        $ids = explode(',', $ids);
        $prikey = 'id';
        $pid = $this->request->post("pid");
        //限制更新的字段
        $field = in_array($field, ['weigh']) ? $field : 'weigh';

        // 如果设定了pid的值,此时只匹配满足条件的ID,其它忽略
        if ($pid !== '') {
            $hasids = [];
            $list = Db::table($table)->where($prikey, 'in', $ids)->where('pid', 'in', $pid)->field('id,pid')->select();
            foreach ($list as $k => $v) {
                $hasids[] = $v['id'];
            }
            $ids = array_values(array_intersect($ids, $hasids));
        }

        $list = Db::table($table)->field("$prikey,$field")->where($prikey, 'in', $ids)->order($field, $orderway)->select();
        foreach ($list as $k => $v) {
            $sour[] = $v[$prikey];
            $weighdata[$v[$prikey]] = $v[$field];
        }
        $position = array_search($changeid, $ids);
        $desc_id = $sour[$position];    //移动到目标的ID值,取出所处改变前位置的值
        $sour_id = $changeid;
        $weighids = array();
        $temp = array_values(array_diff_assoc($ids, $sour));
        foreach ($temp as $m => $n) {
            if ($n == $sour_id) {
                $offset = $desc_id;
            } else {
                if ($sour_id == $temp[0]) {
                    $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
                } else {
                    $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
                }
            }
            $weighids[$n] = $weighdata[$offset];
            Db::table($table)->where($prikey, $n)->update([$field => $weighdata[$offset]]);
        }
        $this->success();
    }

    public function viewsconfig()
    {
        $ids = $this->request->param('ids');
        $info = $this->model->get($ids);
        if(empty($info))
            $this->error(__('Parameter ids can not be empty'));

        $type = $this->request->param('type', null);
        if($type === null)
            $this->error(__('Parameter type can not be empty'));

        $view_row = $info->views($type)->find();

        if(empty($view_row)){
            $this->error(__('未绑定视图!'));
        }

        $fieldList = [];
        $fieldList = collection($view_row->viewsfields)->toArray();//绑定视图字段
        $fieldList = array_merge($fieldList, collection(ViewsfieldsModel::public()->select())->toArray());//绑定共有字段

        $fieldsIds = array_column($fieldList, 'id');//获取字段id
        $fieldsValue = collection($info->viewsFieldsValue()->FieldsIds($fieldsIds)->select())->toArray();//获取到字段的值

        //处理提交
        if ($this->request->isPost()) {
            $row = $this->request->post("row/a");
            if (!$row) {
                $this->error(__('Parameter row can not be empty'));
            }

            $data = [];//私有值
            $dataCommon = [];//共有值
            //循环字段 这里分共有的 和 私有的 值分为私有的 和共有的
            foreach ($fieldList as $value) {
                //判断当前字段是否存在提交的数据里 如果有 保存至data里
                if (isset($row[$value['name']])) {
                    //处理值 如果是选项或者单选之类的 进行处理
                    $row[$value['name']] = is_array($row[$value['name']]) ? implode(',', $row[$value['name']]) : $row[$value['name']];

                    if ($value['common']) { //如果是私有的
                        $tmpData = ['channels_id' => $info->id, 'viewsfields_id' => $value['id'], 'value' => $row[$value['name']]];
                        $field_id = $value['id'];//字段id
                        //值的id
                        $value_id = array_filter($fieldsValue , function($r) use ($field_id){
                            return $r['viewsfields_id'] == $field_id;
                        });
                        //如果栏目和字段的值存在 就表示是更新
                        if (!empty($value_id)) {
                            $value_id = array_merge($value_id);
                            $tmpData['id'] = $value_id[0]['id'];
                        }
                        $data[] = $tmpData;
                    }else{
                        $dataCommon[] = ['id' => $value['id'], 'value' => $row[$value['name']]];
                    }
                }
            }
            try {
                (new Channelsviewvalues)->saveAll($data);
                (new ViewsfieldsModel)->saveAll($dataCommon);
                $this->success();
            } catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
            } catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->error();
        }
        $list = [];
        foreach ($fieldList as $value) {
            if($value['common']){ //如果是私有的值
                $field_id = $value['id'];
                //查找栏目和字段的值相匹配的 并返回二维数组 如果没有 返回空数组
                $feild_value = array_filter($fieldsValue, function($r) use ($field_id){
                    return $r['viewsfields_id'] == $field_id;
                });
                //判断是否有值 如果有就赋值
                if (!empty($feild_value)) { 
                    $feild_value = array_merge($feild_value);
                    $value['value'] = $feild_value[0]['value'];
                }
            }

            //转化数据格式
            if (in_array($value['type'], ['select', 'selects', 'checkbox', 'radio'])) {
                $value['value'] = explode(',', $value['value']);
            }
            $value['content'] = json_decode($value['content'], TRUE);
            $list[] = $value;
        }
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function selectpage()
    {
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $list = $this->model
            ->page($page, $pagesize)
            ->where($where)
            ->select();
            $total = $this->model
            ->where($where)
            ->count();
        }else{
            $list = [];
            foreach ($this->channelsList as $key => $value) {
                $value['name'] = html_entity_decode($value['name']);
                $list[] = $value;
            }
            $total = count($list);
        }
        return json(['list' => $list, 'total' => $total]);
    }
}
